import React, {Component} from 'react';
import axios from 'axios';
import {Progress, notification, Modal, message, Icon} from 'antd';
import CopyToClipboard from 'react-copy-to-clipboard';
import {connect} from 'react-redux';
import styles from './index.module.scss'
import 'antd/dist/antd.css';
import './template/css/fontAwesome.css';
import './template/css/light-box.css';
import './template/css/templatemo-main.css';

var redownload = false;
class ProgressDataList extends Component {
    static displayName = 'ProgressDataList';

    static defaultProps = {};

    constructor(props) {
        super(props);
        this.state = {
            progress: 1,
            progressStatus: 'active',
            visible_redown: false,
            visible: false
        };
    };

    redownload(bool){
        redownload = bool;
        this.setState({
            visible_redown: false,
        });
        console.log("用户选择是否重新下载",redownload);
        if(!redownload){
            window.location.href="tjufe://open virtual experiment";
            /////////////////////////////////////////////////////// this.openNotification();
            /////////////////////////////////////////////////////// this.showModal();
            return;
        }
        localStorage.setItem('tjufe-main', "0");
        this.downloadFile("https://c-t.work/s/be9149f9dcd24f", 'aa');
    };

    openNotification = () => {
        notification.open({
            duration: 15,
            message: '提示信息',
            description:
                '加载过程请耐心等待，加载结束后依照浏览器提示打开仿真程序',
            onClick: () => {
                console.log('显示提示信息...');
            },
        });
    };

    loddingNotification = () => {
        var hasDown = localStorage.getItem('tjufe-main');
        notification.open({
            duration: 60,
            message: '精彩已在路上',
            description:
                '仿真实验程序开启速度由您的浏览器性能决定，如遇杀毒软件误报，请放行程序~',
            onClick: () => {
                console.log('显示提示信息...');
            },
        });
        localStorage.setItem('tjufe-main', "1");
    };

    downFile(blob, fileName) {
        if ('download' in document.createElement('a')) {
            let link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob); // 创建下载的链接
            link.download = fileName; // 下载后文件名
            link.style.display = 'none';
            document.body.appendChild(link);
            link.click(); // 点击下载
            window.URL.revokeObjectURL(link.href); // 释放掉blob对象
            document.body.removeChild(link); // 下载完成移除元素
            this.loddingNotification();
            ///////////////////////////////////////////////////////this.showModal();
        }
    };

    downloadFile(url, data) {
        const _this = this;
        var hasDown = localStorage.getItem('tjufe-main');
        console.log("是否已下载：", hasDown);
        if (hasDown === '1') {
            this.setState({
                visible_redown: true,
            });
            return;
        }
        axios.defaults.withCredentials = false;
        axios({
            url: './main.exe',
            method: 'get',
            responseType: 'blob',
            onDownloadProgress(progress) {
                _this.setState({
                    progress: progress.loaded / 259549759 * 100
                });
            }
        })
            .then(resp => {
                let headers = resp.headers;
                let contentType = headers['content-type'];
                if (!resp.data) {
                    console.error('响应异常：', resp);
                    return false;
                } else {
                    console.error('下载文件：', resp);
                    const blob = new Blob([resp.data], {type: contentType});
                    const contentDisposition = resp.headers['content-disposition'];
                    let fileName = '【点击运行】虚拟仿真实验室.exe';
                    if (contentDisposition) {
                        fileName = window.decodeURI(resp.headers['content-disposition'].split('=')[1]);
                    }
                    console.log('文件名称：', fileName);
                    this.downFile(blob, fileName);
                }
            }).catch(function (error) {
            console.log(error);
        });
        this.openNotification();
    };

    showModal = () => {
        this.setState({
            visible: true,
        });
    };

    hideModal = () => {
        this.setState({
            visible: false,
        });
    };

    scrollToAnchor = (anchorName) => {
        if (anchorName) {
            let anchorElement = document.getElementById(anchorName);
            if(anchorElement) { anchorElement.scrollIntoView(); }
        }
    };

    componentDidMount() {
        axios.get('https://api.tju.ink/website/addaccesslog?url=http://47.105.62.140/tjufe/unity/&marks=实验总量');
        if (this.props.JSESSIONID !== "") {
            this.downloadFile("./NewVirtual.zip", 'aa');
        } else {
            message.error("请您先登录您的账户！");
            window.location.href = "./#/index";
        }
    }

// http://47.105.62.140/document/financial/video/demo.mp4
    render() {
        return (
            <div className={styles.containers}>
                {/*<div className={styles.header}>*/}
                {/*    Made With*/}
                {/*</div>*/}
                <div className={styles.header}>
                    <div className={styles.logo}>
                    </div>
                </div>
                <nav>
                    <div className="logo">

                    </div>
                    <ul  className={styles._ul}>
                        <li><a onClick={this.scrollToAnchor.bind(this,"help1")} className={styles.resetA}><i className="fa fa-internet-explorer"></i> <em>环境配置要求</em></a></li>
                        <li><a onClick={this.scrollToAnchor.bind(this,"help2")} className={styles.resetA}><i className="fa fa-key"></i> <em>程序运行指导</em></a></li>
                        <li><a onClick={this.scrollToAnchor.bind(this,"help4")} className={styles.resetA}><i className="fa fa-briefcase"></i> <em>实验操作步骤</em></a></li>
                    </ul>
                </nav>

                <div className="slides">

                    <div className="slide" id="help1" name="help1">
                        <div className="content second-content">
                            <div className="container-fluid">
                                <div className="col-md-12">
                                    <img src={require('./template/img/help_2.png')} alt="" />
                                </div>
                            </div>
                        </div>
                    </div>

                    <div className="slide" id="help2" name="help2">
                        <div className="content third-content">
                            <div className="container-fluid">
                                <div className="col-md-12">
                                    <img src={require("./template/img/help_3.png")} style={{marginTop: '-2%',width: "100%"}} alt="" />
                                </div>
                            </div>
                        </div>
                    </div>

                    <div className="slide" id="help4" name="help4">
                        <div className="content third-content">
                            <div className="container-fluid">
                                <div className="col-md-12">
                                    <img src={require("./images/back.png")} style={{marginTop: '6%',width: "102%"}} alt="" />
                                </div>
                            </div>
                        </div>
                    </div>
                    {/*<div className="slide" id="help4" name="help4">*/}
                    {/*    <div className="content fourth-content">*/}
                    {/*        <div className="container-fluid">*/}
                    {/*            <div className="row">*/}

                    {/*                <div className="col-md-4 col-sm-6">*/}
                    {/*                    <div className="item">*/}
                    {/*                        <div className="thumb">*/}
                    {/*                            <a href="./template/img/image1_min.png" data-lightbox="image-1"><div className="hover-effect">*/}
                    {/*                                <div className="hover-content">*/}
                    {/*                                    <h2>场景一</h2>*/}
                    {/*                                    <p>政策解读</p>*/}
                    {/*                                </div>*/}
                    {/*                            </div></a>*/}
                    {/*                            <div className="image">*/}
                    {/*                                <img src={require("./template/img/image1.png")} alt="" />*/}
                    {/*                            </div>*/}
                    {/*                        </div>*/}
                    {/*                    </div>*/}
                    {/*                </div>*/}
                    {/*                <div className="col-md-4 col-sm-6">*/}
                    {/*                    <div className="item">*/}
                    {/*                        <div className="thumb">*/}
                    {/*                            <a href="img/image2.png" data-lightbox="image-1"><div className="hover-effect">*/}
                    {/*                                <div className="hover-content">*/}
                    {/*                                    <h2>场景二</h2>*/}
                    {/*                                    <p>财务优化</p>*/}
                    {/*                                </div>*/}
                    {/*                            </div></a>*/}
                    {/*                            <div className="image">*/}
                    {/*                                <img src={require("./template/img/image2_min.png")} alt="" />*/}
                    {/*                            </div>*/}
                    {/*                        </div>*/}
                    {/*                    </div>*/}
                    {/*                </div>*/}

                    {/*            </div>*/}
                    {/*        </div>*/}
                    {/*    </div>*/}
                    {/*</div>*/}
                </div>

                <div className={styles.progress}>
                    <Progress
                        type="line"
                        strokeWidth={24}
                        percent={this.state.progress}
                        showInfo={false}
                        strokeColor={{
                            '0%': '#4DB1D5',
                            '100%': '#4B72EF',
                        }}
                        status={this.state.progressStatus}
                    />
                </div>
                <Modal
                    title="加密程序秘钥（点击复制）"
                    visible={this.state.visible}
                    onOk={this.hideModal}
                    onCancel={this.hideModal}
                    maskClosable={false}
                    footer={null}
                    centered
                >
                    <CopyToClipboard text={this.props.JSESSIONID} onCopy={this.onCopy}>
                        <span style={{cursor: 'pointer'}}><Icon type="key"/>请您妥善保管：{this.props.JSESSIONID}</span>
                    </CopyToClipboard>
                </Modal>
                <Modal
                    title="是否需要重新加载？"
                    centered
                    visible={this.state.visible_redown}
                    onOk={() => this.redownload(true)}
                    onCancel={() => this.redownload(false)}
                    okText="重新加载"
                    okType="dashed"
                    cancelText="直接打开"
                >
                    <p>浏览器检测到您的本地有缓存的仿真实验</p>
                    <p>您可以直接点击下方按钮运行</p>
                </Modal>
            </div>
        );
    }
}

const mapStateToProps = (state) => {
    return {
        JSESSIONID: state.api.JSESSIONID,
    };
};
const mapDispatchToProps = (dispatch) => {
    return {};
};

export default connect(mapStateToProps, mapDispatchToProps)(ProgressDataList);
